package com.lagou.controller;

import com.lagou.pojo.LagouAuthCode;
import com.lagou.pojo.LagouToken;
import com.lagou.service.CodeService;
import com.lagou.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author : liuchangling
 * @Descrition :
 * @Date： Created in 2:41 下午 2022/1/31
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Reference
    private CodeService codeService;

    @GetMapping("/login/{email}/{password}")
    public String login(@PathVariable("email") String email, @PathVariable("password") String password, HttpServletResponse response) {
        LagouToken login = userService.login(email, password);
        if(login==null||login.getToken().isEmpty()){
            return "";
        }
        Cookie cookie=new Cookie("token",login.getToken());
        cookie.setPath("/");
        response.addCookie(cookie);
        return login.getEmail();
    }

    @GetMapping("/isRegistered/{email}")
    public Boolean isRegistered(@PathVariable("email") String email){
        return userService.isRegistered(email);
    }

    @GetMapping("/info/{token}")
    public String info(@PathVariable("token")String token){
        LagouToken info = userService.info(token);
        if(info==null){
            System.out.println("无效token，邮箱不存在");
            return null;
        }
        return info.getEmail();
    }

    @GetMapping("/register/{email}/{password}/{code}")
    public Boolean register(@PathVariable("email") String email, @PathVariable("password") String password, @PathVariable("code") String code, HttpServletResponse response) {
        //校验验证码是否有效
        System.out.println("邮箱:"+email);
        System.out.println("验证码:"+code);
        Integer validate = codeService.validateCode(email, code);
        if (validate != 0) {
            System.out.println("验证码有误");
            return false;
        }
        LagouToken register = userService.register(email, password);
        if (register == null || register.getToken().isEmpty()) {
            return false;
        }
        Cookie cookie = new Cookie("token", register.getToken());
        //设置作用域
        cookie.setPath("/");
        response.addCookie(cookie);
        return true;
    }
}
